package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.ILoginInfoCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Reference
    private ILoginInfoCacheService loginInfoCacheService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.静态资源放行
        if (handler instanceof HandlerMethod) {
            //2.本地session有对象放行
            Object userInfo = request.getSession().getAttribute(Consts.USER_INFO);
            if (userInfo != null) {
                return true;
            }
            //3.查询redis
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(Consts.USER_INFO_TOKEN)) {
                        String token = cookie.getValue();
                        //获取Redis
                        String loginInfo = loginInfoCacheService.getLoginInfo(token);
                        if (loginInfo != null) {
                            userInfo = JSON.parseObject(loginInfo, UserInfo.class);
                            //存入本地session
                            request.getSession().setAttribute(Consts.USER_INFO, userInfo);
                            return true;
                        }
                    }
                }
            }
            //判断资源是否需要登陆访问
            HandlerMethod method = (HandlerMethod) handler;
            if (!method.hasMethodAnnotation(RequiredLogin.class)) {
                return true;
            }
            //判断请求方式
            if (method.hasMethodAnnotation(ResponseBody.class)) {
                //ajax
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(new AjaxResult().mark("请登录后访问").addCode(AjaxResult.NO_LOGIN_CODE)));
            } else {
                //普通请求
                response.sendRedirect("/login.html");
            }
            //拦截
            return false;

        } else {
            return true;
        }
    }
}
